<template>
  <div>
    <el-form
      ref="spuform"
      label-width="80px"
      :inline="false"
      size="normal"
      :rules="formRules"
      :model="spuInfo"
    >
      <el-form-item label="SPU名称" prop="spuName">
        <el-input v-model="spuInfo.spuName"></el-input>
      </el-form-item>
      <el-form-item label="SPU品牌" prop="tmId">
        <el-select v-model="spuInfo.tmId" size="small">
          <el-option
            :value="item.id"
            :label="item.tmName"
            v-for="item in trademarkList"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input type="textarea" v-model="spuInfo.description"></el-input>
      </el-form-item>
      <el-form-item label="上传图片">
        <el-upload
          multiple
          :file-list="spuImageList"
          :action="`${$BASE_API}/admin/product/fileUpload`"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleUploadSuccess"
        >
          <i class="el-icon-upload"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          v-model="addAttr"
          style="margin: 0 10px 10px 0"
          size="small"
          :placeholder="`还有${unChoiceAttr.length}项没选择`"
        >
          <el-option
            :value="item.id + ':' + item.name"
            :label="item.name"
            v-for="item in unChoiceAttr"
            :key="item.id"
          ></el-option>
        </el-select>
        <el-button type="primary" size="small" @click="addAttrValueList"
          >添加属性值</el-button
        >
        <el-table border stripe :data="spuInfo.spuSaleAttrList">
          <el-table-column
            label="序号"
            align="center"
            type="index"
            width="100"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="120"
            align="center"
            prop="saleAttrName"
          ></el-table-column>
          <el-table-column label="属性值">
            <template slot-scope="{ row, $index }">
              <el-tag
                type="warning"
                :key="attrValue.id"
                v-for="(attrValue, index) in row.spuSaleAttrValueList"
                closable
                style="margin-right: 10px"
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
                >{{ attrValue.saleAttrValueName }}
              </el-tag>
              <el-input
                size="small"
                v-model="row.saleAttrValueName"
                :ref="$index"
                style="width: 90px; margin-left: 10px; vertical-align: bottom"
                v-show="row.flag"
                @keyup.enter.native="toBtn(row, $index)"
                @blur="toBtn(row, $index)"
              ></el-input>
              <el-button
                size="mini"
                icon="el-icon-plus"
                @click="toEdit(row, $index)"
                v-show="!row.flag"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
            ></el-button>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="save">保存</el-button>
        <el-button size="small" @click="cance">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      trademarkList: [],
      spuId: "",
      spuInfo: {
        // SPU详情信息对象
        category3Id: null, // 3级分类ID
        spuName: "", // spu名称
        description: "", // spu描述
        tmId: null, // spu的品牌id
        spuSaleAttrList: [], // spu的销售属性列表
        spuImageList: [], // spu图片列表
      },
      addAttr: "",
      spuImageList: [],
      attrList: [],
      formRules: {
        spuName: [
          { required: true, message: "请输入spu名称", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入spu描述", trigger: "blur" },
        ],
        tmId: [{ required: true, message: "请选择品牌名称", trigger: "blur" }],
      },
      show: true,
    };
  },
  computed: {
    unChoiceAttr() {
      const { attrList } = this;
      const { spuSaleAttrList } = this.spuInfo;
      let arr = attrList.filter((item) => {
        let haveArr = spuSaleAttrList.some(
          (attr) => item.name === attr.saleAttrName
        );
        return !haveArr;
      });
      return arr;
    },
  },
  methods: {
    /* 
    上传图片成功后的回调
    response: 请求响应对象
    file: 当前上传成功的图片对象
    fileList: 所有已上传的图片对象的数组
    */
    handleUploadSuccess(response, file, fileList) {
      this.spuImageList = fileList;
    },

    /* 
    点击删除图片的回调函数
    file: 被删除的图片对象
    fileList: 剩下的图片对象的数组
    */
    handleRemove(file, fileList) {
      this.spuImageList = fileList;
    },
    /* 
    显示指定的大图片
    file: 包含图片信息的对象
    */
    handlePictureCardPreview(file) {
      // 指定要显示的大图url
      this.dialogImageUrl = file.url;
      // 显示大图dilaog
      this.dialogVisible = true;
    },
    reset() {
      this.dialogImageUrl = "";
      this.dialogVisible = false;
      this.trademarkList = [];
      this.spuInfo = {
        // SPU详情信息对象
        category3Id: null, // 3级分类ID
        spuName: "", // spu名称
        description: "", // spu描述
        tmId: null, // spu的品牌id
        spuSaleAttrList: [], // spu的销售属性列表
        spuImageList: [], // spu图片列表
      };
      this.addAttr = "";
      this.spuImageList = [];
      this.attrList = [];
      this.formRules = {
        spuName: [
          { required: true, message: "请输入spu名称", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入spu描述", trigger: "blur" },
        ],
        tmId: [{ required: true, message: "请选择品牌名称", trigger: "blur" }],
      };
      this.show = true;
      this.spuId = "";
    },

    //添加属性值
    addAttrValueList() {
      const [baseSaleAttrId, saleAttrName] = this.addAttr.split(":");
      this.addAttr = "";
      // this.attrList.splice((this.attrList.findIndex(item=>saleAttrName==item.name)),1);

      const attr = {
        baseSaleAttrId,
        saleAttrName,
        flag: false,
        spuSaleAttrValueList: [],
      };
      this.spuInfo.spuSaleAttrList.push(attr);
      this.addAttrValue = "";
    },
    //添加属性+按钮回调
    toEdit(row, index) {
     if (row.hasOwnProperty('edit')) {
       row.flag = true
      } else {
        this.$set(row, 'flag', true)
      }
      row.flag = true;
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },
    //添加属性ipt框回调
    toBtn(row, index) {
      const { saleAttrValueName, baseSaleAttrId } = row;
      if (!saleAttrValueName || saleAttrValueName.trim() === "") {
        row.flag = false;
        return;
      }
      let repet = row.spuSaleAttrValueList.some(
        (item) => item.saleAttrValueName.trim() === saleAttrValueName.trim()
      );
      if (repet) {
        this.$message.error("属性值不能重复");
        return;
      }
      let newAddAttrValue = {
        baseSaleAttrId,
        saleAttrValueName,
      };
      row.spuSaleAttrValueList.push(newAddAttrValue);
      row.saleAttrValueName = "";
      row.flag = false;
    },
    //获取全部品牌
    async getTrademarkList() {
      let res = await this.$API.spu.getTardmakeList();
      this.trademarkList = res.data;
    },
    //获取全部销售属性
    async getAttrList() {
      let res = await this.$API.spu.getSaleAttrList();
      this.attrList = res.data;
    },
    //获取spu详细信息
    async getSpuInfo() {
      let res = await this.$API.spu.get(this.spuId);
      Object.assign(this.spuInfo, res.data);
    },
    //获取某个spu下的图片
    async getImg() {
      const result = await this.$API.spu.getSpuImageList(this.spuId);
      const spuImageList = result.data;
      spuImageList.forEach((item) => {
        item.name = item.imgName;
        item.url = item.imgUrl;
      });
      this.spuImageList = spuImageList;
    },
    initAddSpu(c3Id) {
      this.spuInfo.category3Id = c3Id;
      this.getTrademarkList();
      this.getAttrList();
    },
    initUpdateSpu(spu) {
      this.spuId = spu.id;
      this.getTrademarkList();
      this.getAttrList();
      this.getSpuInfo();
      this.getImg();
    },
    //保存按钮回调
    save() {
      const { spuInfo, spuImageList } = this;
      spuInfo.spuImageList = spuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: item.response ? item.response.data : item.imgUrl,
        };
      });
      spuInfo.spuSaleAttrList.forEach((item) => {
        delete item.flag;
      });
      this.$refs.spuform.validate(async (v) => {
        if (v) {
          try {
            await this.$API.spu.addUpdate(spuInfo);
            this.$message.success(spuInfo.id ? "修改成功" : "添加成功");
            this.$emit("changescene");
            this.$emit('success',this.spuId)
            this.reset();
          } catch (error) {
            this.$message.error(error.message);
          }
        }
      });
    },
    cance() {
      this.$emit("changescene");
      this.reset();
      this.$nextTick(() => {
        this.$refs.spuform.clearValidate();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
</style>